<?php
session_start();
require_once 'db_connect.php';
require_once 'HerbManager.php';

// 检查用户是否已登录
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => '只允许POST请求']);
    exit;
}

try {
    $herbManager = new HerbManager();
    
    // 获取POST数据
    $id = $_POST['id'] ?? '';
    $name = trim($_POST['name'] ?? '');
    $purchase_price = $_POST['purchase_price'] ?? '';
    $sale_price = $_POST['sale_price'] ?? '';
    $shipping = $_POST['shipping'] ?? '包邮';
    $category_price = $_POST['category_price'] ?? '';
    $effects = trim($_POST['effects'] ?? '');
    $contraindications = trim($_POST['contraindications'] ?? '');
    
    // 验证必填字段
    $errors = [];
    
    if (empty($name)) {
        $errors['name'] = '药材名称不能为空';
    }
    
    if (!empty($purchase_price) && (!is_numeric($purchase_price) || $purchase_price < 0)) {
        $errors['purchase_price'] = '进货价必须是非负数';
    }
    
    if (!empty($sale_price) && (!is_numeric($sale_price) || $sale_price < 0)) {
        $errors['sale_price'] = '售价必须是非负数';
    }
    
    if (!empty($category_price) && (!is_numeric($category_price) || $category_price < 0)) {
        $errors['category_price'] = '类目售价必须是非负数';
    }
    
    // 检查是否有验证错误
    if (!empty($errors)) {
        echo json_encode([
            'success' => false,
            'message' => '数据验证失败',
            'errors' => $errors
        ]);
        exit;
    }
    
    // 检查药材名称是否重复（排除当前编辑的药材）
    $currentHerb = $herbManager->getHerbById($id);
    if (!$currentHerb) {
        echo json_encode([
            'success' => false,
            'message' => '药材不存在'
        ]);
        exit;
    }
    
    if ($name !== $currentHerb['name']) {
        // 检查新名称是否与其他药材重复
        $existingHerbs = $herbManager->searchHerbs($name);
        foreach ($existingHerbs as $herb) {
            if ($herb['id'] != $id && $herb['name'] === $name) {
                echo json_encode([
                    'success' => false,
                    'message' => '药材名称已存在，请使用不同的名称'
                ]);
                exit;
            }
        }
    }
    
    // 准备更新数据
    $updateData = [
        'name' => $name,
        'purchase_price' => $purchase_price ?: null,
        'sale_price' => $sale_price ?: null,
        'shipping' => $shipping,
        'category_price' => $category_price ?: null,
        'effects' => $effects ?: null,
        'contraindications' => $contraindications ?: null
    ];
    
    // 执行更新
    if ($herbManager->updateHerb($id, $updateData)) {
        // 在返回数据中添加ID，这样前端就能找到对应的药材卡片
        $updateData['id'] = $id;
        echo json_encode([
            'success' => true,
            'message' => '药材更新成功',
            'data' => $updateData
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => '药材更新失败'
        ]);
    }
    
} catch (Exception $e) {
    error_log('编辑药材错误: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => '系统错误：' . $e->getMessage()
    ]);
}
?>
